import { message, Modal, Upload } from 'antd';
import React, { useState } from 'react';
import { baseURL } from 'utils/request';
import { getToken } from 'utils/storage';
import { UploadOutlined } from '@ant-design/icons';
export default function Test() {
  const [imgSrc, setImgSrc] = useState('');
  const [fileList, setFileList] = useState([]);
  const props = {
    name: 'image',
    accept: '.jpg,.jpeg,.png', //用于设定筛选用户上传时的文件格式
    action: `${baseURL}/v1_0/upload`,
    headers: {
      authorization: `Bearer ${getToken()}`,
    },
    onChange(info) {
      console.log(info);
      setFileList(info.fileList);
      if (info.file.status === 'done') {
        message.success(`${info.file.name} 上传成功`);
      } else if (info.file.status === 'error') {
        message.error(`${info.file.name} 上传失败`);
      }
    },
    onPreview(file) {
      setImgSrc(file.thumbUrl);
    },
    beforeUpload(file, fileList) {
      // console.log(file);
      const imgs = ['image/png', 'image/jpg', 'image/jpeg'];
      if (!imgs.includes(file.type)) {
        message.warning('不支持的图片格式', 1);
        return Upload.LIST_IGNORE; //阻止发请求。也不显示在前端界面上
      }
      if (file.size > 1024 * 1024) {
        message.warning('图片不能大于1mb', 1);
        return Upload.LIST_IGNORE;
      }
    },
  };
  return (
    <>
      <Upload {...props} listType="picture-card" fileList={fileList}>
        {fileList.length === 3 ? null : <UploadOutlined />}
      </Upload>
      <Modal
        title="预览"
        visible={!!imgSrc}
        footer={null}
        onCancel={() => setImgSrc('')}
      >
        <img
          src={imgSrc}
          alt=""
          style={{
            width: '100%',
          }}
        />
      </Modal>
    </>
  );
}
